package com.liumin.comlink.http;


import com.liumin.comlink.BuildConfig;
import com.liumin.comlink.http.intercepter.AddCookiesInterceptor;
import com.liumin.comlink.http.intercepter.BasicParamsInterceptor;
import com.liumin.comlink.http.intercepter.GzipRequestInterceptor;
import com.liumin.comlink.http.intercepter.LogInterceptor;
import com.liumin.publiclib.helper.ContextApp;
import com.readystatesoftware.chuck.ChuckInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * retrofit初始化
 * 2019/12/25 11:13
 *
 * @author LiuWeiHao
 */
public class RetrofitUtil {
    private static Retrofit retrofit;
    private static Retrofit.Builder builder;
    private static String baseUrl;

    public static void setBaseUrl(String baseUrl) {
        RetrofitUtil.baseUrl = baseUrl;
    }

    public static Retrofit init() {
        if (retrofit == null) {
            synchronized (RetrofitUtil.class) {
                if (retrofit == null) {
                    builder = new Retrofit.Builder()
                            .baseUrl(baseUrl)
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .client(getClient());
                    retrofit = builder.build();
                }
            }
        }
        return builder.build();
    }


    /**
     * Created by LWH at 2017/8/24 00:16
     * 设置client和拦截器
     */
    private static OkHttpClient getClient() {
        //添加公共请求参数
        BasicParamsInterceptor basicParamsInterceptor = new BasicParamsInterceptor.Builder()
                //添加公共参数到消息头
                .addHeaderParam("terminal", "Android")
                .addHeaderParam("Content-Encoding", "gzip")
                .addHeaderParam("Transfer-Encoding", "chunked")
                .build();
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder
//              .addInterceptor(new ReceivedCookiesInterceptor())
                .addInterceptor(basicParamsInterceptor)
                .addInterceptor(new AddCookiesInterceptor())
                .addInterceptor(new GzipRequestInterceptor());
        builder.addInterceptor(new ChuckInterceptor(ContextApp.app()));
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new LogInterceptor());
        }
        builder.readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS);
        return builder.build();
    }

}
